package adavance.thread.bank;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//取钱人
public class Taker extends Thread {
    private final Account ac;
    //策略锁
    private static final Lock lock = new ReentrantLock();

    public Taker(String name, Account a) {
        super(name);
        this.ac = a;
    }

    @Override
    public void run() {
        Random r = new Random();
        int qu = 0;
        while (ac.getMoney() > 0) {
            qu = r.nextInt(200);
            try {
                lock.lock();
                if (ac.getMoney() >= qu) {
                    //钱还够，可以取
                    try {
                        sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ac.withdraw(qu);
                    System.out.println(super.getName() + "取钱" + qu + "元，当前账户余额是：" + ac.getMoney() + "元");
                }
            } finally {
                lock.unlock();
            }

        }
    }
}
